import axios from "axios";

export const DIRECTUS_URL = (
  (import.meta.env.VITE_DIRECTUS_URL as string) || "/directus"
).replace(/\/+$/, "");
export const DIRECTUS_TOKEN =
  (import.meta.env.VITE_DIRECTUS_STATIC_TOKEN as string | undefined)?.trim() ||
  "";

export const directus = axios.create({
  baseURL: DIRECTUS_URL,
  withCredentials: false,
  headers: { Accept: "application/json" },
});

directus.interceptors.request.use((config) => {
  if (DIRECTUS_TOKEN) {
    config.headers = {
      ...(config.headers || {}),
      Authorization: `Bearer ${DIRECTUS_TOKEN}`,
    };
  }
  return config;
});

/** 将 filter 递归展开为 URLSearchParams，支持对象 & 数组 */
export function appendFilterParams(
  params: URLSearchParams,
  value: any,
  path: string[] = []
) {
  if (Array.isArray(value)) {
    value.forEach((v, i) =>
      appendFilterParams(params, v, [...path, String(i)])
    );
    return;
  }
  // 对象：继续深入
  if (value !== null && typeof value === "object") {
    Object.entries(value).forEach(([k, v]) => {
      appendFilterParams(params, v, [...path, k]);
    });
    return;
  }
  const key = `filter[${path.join("][")}]`;
  params.set(key, String(value));
}

export function appendFields(params: URLSearchParams, fields: string[]) {
  fields.forEach((f) => params.append("fields[]", f));
}

export function idsToCsv(ids: (string | number)[]) {
  return (ids || []).map(String).join(",");
}

/** 通用查询 */
export async function getItems<T = any>(
  collection: string,
  query?: URLSearchParams | Record<string, any>
): Promise<{ data: T[]; meta?: any }> {
  const searchParams =
    query instanceof URLSearchParams
      ? query
      : (() => {
        const p = new URLSearchParams();
        if (query?.fields && Array.isArray(query.fields))
          appendFields(p, query.fields);
        if (query?.filter) appendFilterParams(p, query.filter);
        if (query?.page) p.set("page", String(query.page));
        if (query?.limit) p.set("limit", String(query.limit));
        if (query?.sort) p.set("sort", String(query.sort));
        if (query?.meta) {
          (Array.isArray(query.meta) ? query.meta : [query.meta]).forEach(
            (m: string) => p.append("meta", m)
          );
        }
        if (query?.search) p.set("search", String(query.search));
        return p;
      })();

  const url = `/items/${collection}?${searchParams.toString()}`;
  const { data } = await directus.get(url, {
    headers: { "Cache-Control": "no-cache" },
  });
  return { data: data?.data ?? [], meta: data?.meta };
}

export async function getItemById<T = any>(
  collection: string,
  id: string | number,
  fields?: string[]
) {
  const params = new URLSearchParams();
  if (fields?.length) appendFields(params, fields);
  const url = `/items/${collection}/${id}${params.toString() ? `?${params.toString()}` : ""}`;
  const { data } = await directus.get(url);
  return data?.data as T;
}

export async function createItem<T = any>(
  collection: string,
  payload: Partial<T>
) {
  const { data } = await directus.post(`/items/${collection}`, payload);
  return data?.data as T;
}

export async function createItems<T = any>(
  collection: string,
  payloads: Partial<T>[]
) {
  const { data } = await directus.post(`/items/${collection}`, payloads);
  return data?.data as T[];
}

export async function updateItem<T = any>(
  collection: string,
  id: string | number,
  payload: Partial<T>
) {
  const { data } = await directus.patch(`/items/${collection}/${id}`, payload);
  return data?.data as T;
}

export async function updateItems<T = any>(
  collection: string,
  payloads: Array<Partial<T> & { id: string | number }>
) {
  const { data } = await directus.patch(`/items/${collection}`, payloads);
  return data?.data as T[];
}

export async function deleteItem(collection: string, id: string | number) {
  const { data } = await directus.delete(`/items/${collection}/${id}`);
  return data?.data;
}

/**
 * ✅ 批量删除
 */
export async function deleteItems(
  collection: string,
  ids: (string | number)[]
) {
  const { data } = await directus.delete(`/items/${collection}`, {
    data: { keys: ids },
  });
  return data?.data;

}
